package com.bestv.search.spider.youku.util;

import com.bestv.search.spider.util.SpiderConst;
import com.bestv.search.spider.util.SpiderUtil;
import com.bestv.search.spider.util.StringUtil;
import com.bestv.search.spider.youku.model.YouKuAppKey;
import com.bestv.search.spider.youku.model.YouKuGenre;
import com.bestv.search.spider.youku.model.YouKuType;
import net.sf.json.JSONArray;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

public class YouKuUtil extends SpiderUtil {

    private final Log log = LogFactory.getLog(YouKuUtil.class);

    public static String[] getSyncAreas() {
        return new String[]{"大陆", "香港", "台湾", "韩国", "美国", "法国", "英国", "德国", "意大利", "加拿大", "印度", "俄罗斯", "泰国", "其他"};
    }

    public static int[] getSyncYears() {
        // gets videos last 40 years
        int length = 40;

        Calendar c = Calendar.getInstance();
        int currYear = c.get(Calendar.YEAR);
        int[] years = new int[length];
        for (int i = 0; i < length; i++) {
            years[i] = currYear - i;
        }
        return years;
    }

    /**
     * @return Key-value map, key is type(电影,电视剧 ,动漫)，value is genre
     * type(喜剧，动作）。
     */
    public static Map<String, YouKuGenre[]> getSyncGenreTypes() {
        Map<String, YouKuGenre[]> result = new Hashtable<String, YouKuGenre[]>();

        String response = null;

        do {
            // Gets all YouKuType
            response = new YouKuUtil().sendRequest(SpiderConst.YOUKU_SHOW_SCHEMA_CATEGORY_URL);
        } while (response == null);

        if (response != null && !response.equalsIgnoreCase(SpiderConst.EMPTY)) {
            // Convert to native string.
            response = StringUtil.ascii2Native(response);

            // Convert to JSONArray text
            response = StringUtil.convertToJSONArrayText(response);

            JSONArray json = JSONArray.fromObject(StringUtil.ascii2Native(response));
            @SuppressWarnings("unchecked")
            List<YouKuType> types = (List<YouKuType>) JSONArray.toCollection(json, YouKuType.class);
            for (YouKuType type : types) {
                // Just get genres of 电影,电视剧 ,动漫
                if (SpiderConst.MOVIES.equalsIgnoreCase(type.getTerm())
                        || SpiderConst.TV.equalsIgnoreCase(type.getTerm())
                        || SpiderConst.ANIME.equalsIgnoreCase(type.getTerm())) {
                    result.put(type.getLabel(), type.getGenre());
                }
            }
        }

        return result;
    }

    public String sendRequestByAppKey(String url) {
        YouKuAppKey key = YouKuAppKeyPool.getAppKey();
        if (key == null) {
            log.warn("API key is busy, please wait....");
            return null;
        } else {
            StringBuffer buffer = null;
            if (url.endsWith(SpiderConst.QUESTION_MARK)) {
                buffer = StringUtil.buildBuffer(new String[]{url, SpiderConst.YOUKU_CLIENT_ID,
                        SpiderConst.EQUAL_FLAG, key.getKeyId()});
            } else {
                buffer = StringUtil.buildBuffer(new String[]{url, SpiderConst.URL_SPLIT_FLAG,
                        SpiderConst.YOUKU_CLIENT_ID, SpiderConst.EQUAL_FLAG, key.getKeyId()});
            }
            return sendRequest(buffer.toString());
        }
    }
}